package fr.jade.fraclite;

import java.util.Map;

import org.objectweb.fractal.api.Component;
import org.objectweb.fractal.api.NoSuchInterfaceException;
import org.objectweb.fractal.api.Type;
import org.objectweb.fractal.api.factory.InstantiationException;

import fr.jade.fraclite.api.Controller;

/**
 * Provides a basic implementation of the {@link Component} interface.
 * <br>
 * <br>
 * <b>Requirements</b>
 * <ul>
 * <li>none.</li>
 * </ul>
 */

public class BasicComponent implements Controller, Component {

  /**
   * The type of this component.
   */

  public Type fcType;

  /**
   * The interfaces of this component. This map associates each interface to its
   * name.
   */

  public Map fcInterfaces;

  /**
   * Initializes the fields of this mixin from the given context, and then calls
   * the overriden method.
   * 
   * @param ic information about the component to which this controller object
   *      belongs.
   * @throws InstantiationException if the initialization fails.
   */

  public void initFcController (final InitializationContext ic) throws InstantiationException {
    this.fcType = ic.type;
    this.fcInterfaces = ic.interfaces;
  }

  public Type getFcType () {
    return fcType;
  }

  public Object[] getFcInterfaces () {
    if (fcInterfaces == null) {
      return new Object[0];
    }
    // returns the names of all the public interfaces in fcInterfaces
    // interfaces whose name begins with '/' are private
    int size = 0;
    String[] names = new String[fcInterfaces.size()];
    names = (String[])fcInterfaces.keySet().toArray(names);
    for (int i = 0; i < names.length; ++i) {
      if (names[i].charAt(0) != '/') {
        ++size;
      }
    }
    int index = 0;
    Object[] itfs = new Object[size];
    for (int i = 0; i < names.length; ++i) {
      if (names[i].charAt(0) != '/') {
        itfs[index++] = fcInterfaces.get(names[i]);
      }
    }
    return itfs;
  }

  public Object getFcInterface (final String interfaceName) throws NoSuchInterfaceException {
    Object itf = fcInterfaces == null ? null : fcInterfaces.get(interfaceName);
    if (itf == null) {
      throw new ChainedNoSuchInterfaceException(null, this, interfaceName);
    }
    return itf;
  }

}
